#!/bin/sh
function Error_Msg()
{
    error_msg=$1
    echo error_message=$error_msg
    curl -H "Content-Type:application/json"  -X POST --data  '{"errorinfo": [{"error_message":"'"$error_msg"'","jid":"'$rp_jid'"}]}'  "$notify_url"
    exit 1
}

function upload_file_ftp()
{
    dst_dir=$1
    ftp_dir=$2

    [ -d $ftp_dir ] && rm -rf $ftp_dir
    mkdir $ftp_dir
    if [ -d target ] && [ "x`ls target`" != "x" ];then #target目录存在且不为空
        cp -rn  target/* $ftp_dir/
    else
        error_message="have no target or target is empty and will exit"
        Error_Msg "$error_message"
    fi
    ls $ftp_dir
    start_time=`date +%s`
    ftp_pwd=$dst_dir/$ftp_dir
    if [ "$3" == "1" ]; then #只有正式环境的包才在ftp上备份完整包,即=1
        echo create folder $ftp_dir under $dst_dir
        curl -u aolingli:ALL1234! ftp://192.168.8.251/output/$ftp_pwd/ --ftp-create-dirs #创建远程目录
        echo upload file under $ftp_dir and upload to $dst_dir
    fi
    if [ -d $ftp_dir ] && [ "x`ls $ftp_dir`" != "x" ];then
        cd $ftp_dir
        for upload_file in `ls`
        do
            if [ -d "$upload_file" ];then #如果上传文件为文件夹，则先压缩
                echo "$upload_file" is a directory and need to compress
                zip -q -r "$upload_file".zip "$upload_file"
                rm "$upload_file" -rf
                upload_file="$upload_file".zip
            fi
            if [ "$3" == "1" ]; then #只有正式环境的包才在ftp上备份完整包,即=1
                echo upload_file=$upload_file
                curl -u aolingli:ALL1234! -T "$upload_file"  ftp://192.168.8.251/output/$ftp_pwd/
            else
                echo only release env need backup all pkg to ftp but is not release env
            fi
        done
        [ "$3" == "1" ] && echo ftp_path="ftp://192.168.8.251/output/$dst_dir/$ftp_dir/"
    else
        error_message="have no target or target is empty and will exit"
        Error_Msg "$error_message"
    fi

    end_time=`date +%s`
    cost=$(( $end_time - $start_time )) #计算传包用时
    echo "upload Done. Total costs $cost seconds."
}

echo start build chong phoenix channel=$1,type=$2,tag=$3
source /etc/profile
echo jenkins var as follow:
echo build_num=$BUILD_NUMBER
echo build_user_id=$BUILD_USER_ID
echo build_user=$BUILD_USER
echo job_name=$JOB_NAME
dir_path=`pwd`
cdn_ftp_server="http://cdn.hpplay.com.cn/jenkins_result"
cdn_ftp_path="lebotest@120.76.155.128:/lebores/jenkins_result"
ftp_psw="lebo123" #CDN密码
cdn_ftp_server_test="http://cdn.hpplay.com.cn/jenkins_result_test"
cdn_ftp_path_test="lebotest@120.76.155.128:/lebores/jenkins_result_test"
re_url=`cat re_url_info`
notify_url_release=$re_url
notify_url_test="http://120.79.212.106:9201/JenkinsCallback"
#notify_url_test="http://192.168.40.246:9201/JenkinsCallback"
release_flag=0
ph_ftp_dir=phoenix_sdk/released_version/2019_custom_release
if [ "$JOB_NAME" != "Yun-Reciever-Sdk" ];then
    echo ================Test Project===========
    ftp_server=$cdn_ftp_server_test
    ftp_path=$cdn_ftp_path_test
    notify_url=$notify_url_test
else
    ftp_server=$cdn_ftp_server
    ftp_path=$cdn_ftp_path
    notify_url=$notify_url_release
    release_flag=1
fi
phoenix_path=$ftp_path/phoenix_sdk
sdk_server=$ftp_server/phoenix_sdk
echo phoenix_path=$phoenix_path
echo sdk_server=$sdk_server
export REPO_URL='https://mirrors.tuna.tsinghua.edu.cn/git/git-repo/'
sdk_tag=$3
echo sdk_tag=$sdk_tag
if [ "x$sdk_tag" != "x" ]; then
    echo use tag:$sdk_tag to get repo 
    repo init -u gerrit:phoenix/manifest -b refs/tags/$sdk_tag
    [ $? -ne 0 ] && error_message="get tag $sdk_tag failed and exit" && Error_Msg "$error_message"
    echo repo config :
    cat .repo/manifest.xml
    repo sync -j4
    repo start $sdk_tag --all
    repo checkout $sdk_tag
    repo branches
    ph_branch_tmp=$sdk_tag
else
    error_message="have no tag and exit"
    Error_Msg "$error_message"
fi

echo ========manifest branches/tag========= > sdk_info
echo manifest_tag=$3 >> sdk_info
echo >> sdk_info
echo ========repos branches========= >> sdk_info
cat .repo/manifest.xml |grep project |awk -F "project " '{print $2}' |awk -F "name=" '{print $1}' |sed s/"\""//g >> sdk_info
echo >> sdk_info
repo_list="SDK SDK/base/upnp SDK/android/sink/sdk-api SDK/android/sink/common SDK/android/sink/SDK-sample"
echo ========repos commit id========= >> sdk_info
for repo_path in $repo_list
do
    cd $dir_path/$repo_path
    echo $repo_path commit id=`git rev-parse HEAD` >> $dir_path/sdk_info
done
cd $dir_path
echo >> sdk_info
echo ========build config========= >> sdk_info
cat interface_info >> sdk_info

du -sh 
cp sdk_config SDK/
cp interface_info SDK/
cd SDK/

phoenix_channel=$1
phoenix_type=$2
dir_name=$phoenix_channel
sdk_path=`pwd`
echo sdk now path=$sdk_path


now_time=`date "+%Y%m%d%H%M"`
commit=`git rev-parse --short HEAD`
ph_branch=`echo $ph_branch_tmp |sed 's/\.//g'` #删除分支名或者tag中的点符号
now_time="$now_time"_"custom"_"$ph_branch"_"$commit"_"$dir_name"_"$phoenix_type"
echo ftp dir name is $now_time

[ -f gradlew ] && chmod 777 gradlew
cp /usr/local/scripts/build_scripts/local.properties android/sink/

chmod 777 build.sh
git status
git diff
echo "build_channle=$phoenix_channel"
if  [ -f feature.sh ]; then 
    echo interface_info as follow:
    cat interface_info
    build_options_tmp=`cat interface_info |grep "build_option:" |awk -F ":" '{print $2}' |sed s/LEBO_OPTION_[0-9]=//g|sed s/"OPTION_USE_LELINKPLAYER="//g`
    if [ "x`echo $build_options_tmp |grep LEBO_OPTION_`" != "x" ]; then #不为空，说明参数变量后缀是两位数
        echo $build_options_tmp  need more deal with
        build_options=`echo $build_options_tmp |sed s/LEBO_OPTION_[0-9][0-9]=//g`
    else
        build_options=$build_options_tmp
    fi

    build_actions=`cat interface_info |grep "build_action:" |awk -F ":" '{print $2}' |sed s/LEBO_ACTION_[0-9]=//g|sed s/LBEO_ACTION_[0-9]=//g`
    echo build_options is $build_options and build_actions is $build_actions
    [ "x$build_options" == "x" ] && build_interfaces="$build_actions" && echo actions:$build_interfaces 
    [ "x$build_actions" == "x" ] && build_interfaces="$build_options" && echo options:$build_interfaces
    [ "x$build_options" != "x"  -a "x$build_actions" != "x" ] && build_interfaces="$build_options,$build_actions" && echo all: $build_interfaces
    echo build_interfaces is $build_interfaces
    if [ "x`echo $build_interfaces |grep LEBO_`" != "x" ]; then #不为空,说明没处理正确
        error_message="$build_interfaces also have illeage string, so exit"
        Error_Msg "$error_message"
    fi
    echo deal with feature.sh and run it 
    dos2unix feature.sh android/sink/feature.sh
    chmod 777 feature.sh android/sink/feature.sh
fi
sed -i 's/,/\n/g' sdk_config
echo sdk config as follow:
cat sdk_config
have_ijk=`cat sdk_config |grep have_ijk |awk -F "=" '{print $2}'`
have_custom=`cat sdk_config |grep have_custom |awk -F "=" '{print $2}'`
have_free=`cat sdk_config |grep have_free |awk -F "=" '{print $2}'`
player_ui=`cat sdk_config |grep player_ui |awk -F "=" '{print $2}'`
have_domain=`cat sdk_config |grep have_domain |awk -F "=" '{print $2}'`
have_dlna=`cat sdk_config |grep have_dlna |awk -F "=" '{print $2}'`
have_conference=`cat sdk_config |grep have_conference |awk -F "=" '{print $2}'`
update_zip=0
# 参数需要为key value 形式，可参考如下 base 目录下的 build.sh
#channel:leboapk,buildtype:release,demoName:demo,onlybuild:0,ijk:1,free:1,playerUI:1,bangcleFile:2,domain:0
# channel:     渠道，默认是happytest
# buildtype:   release or debug，默认是debug
# demoName:    demo名称，demo,demo-raw,demo-player,demo-jar,demo-ding,demo-option 默认是demo
# onlybuild:   1 build&install ; 0 build only，默认是1
# ijk:         是否需要ijk 1需要，0不需要，2不需要liblbffmpeg.so(满足sdk包尽量小的需求) 默认1
# free:        是否是免费版本sdk    1 免费，0不免费。默认1
# playerUI:    是否使用乐播播放UI   1 是，0否。默认1
# bangcleFile: 加固策略   0都不加固，1加固so及aar， 2仅加固so， 3仅加固aar，默认2
# domain:      域名配置   0乐播域名，1 CIBN域名   默认0
# dlna: dlna开关生效值配置，1表示默认的dlna开关生效值配置（0(关)/1(开)），2 表示修改dlna生效开关值（8888(关)/9999(开)）
# updateZip: 升级包制作，0 默认只有一个升级包，大于0 打包多个升级包（当前api版本递减），默认0
# conference: 是否是conference版本,1是，0不是。默认0
#如果demoName是demo-option时，所有接口都要打开，即不执行feature.sh即可
if [ "$have_custom" == "demo-option" ];then
    echo need open all interfaces and not run feature.sh
else
    echo this is not demo-option and run feature.sh
    echo build_interfaces is $build_interfaces
    sh feature.sh "$build_interfaces"
fi
#如果demoName是demo-conference,即会议室方案，必须为收费版
if [ "$have_custom" == "demo-conference" ];then
    have_free=0 #收费
    have_conference=1 #是tob
fi
build_var="channel:$phoenix_channel,buildtype:$phoenix_type,demoName:$have_custom,onlybuild:0,ijk:$have_ijk,free:$have_free,playerUI:$player_ui,bangcleFile:0,domain:$have_domain,dlna:$have_dlna,updateZip:$update_zip,conference:$have_conference"
echo build_var=$build_var 
echo build_var=$build_var >> $dir_path/sdk_info
echo valid_interface=`cat android/sink/sdk-api/src/main/assets/hpplay/dat/feature.dat` >> $dir_path/sdk_info
sh build.sh $build_var |tee build_result

echo check scripts build resutlt
if [ "x`grep -rn "BUILD FAILED" build_result`" != "x" ];then #如果打包过程输出重定向文件build_result中有‘BUILD FAILED’字段，那么表示构建失败，退出
    error_message="build status is BUILD FAILED, so exit"
    Error_Msg "$error_message"
fi

cp android/sink/sdk-api/libs target/ -rn  #release的接收端sdk要回收libs
cp $dir_path/sdk_info target
cp target target_all -rn
mv target target_tmp
mkdir target
mv  target_tmp/*.tar  target_tmp/*.aar  target_tmp/*.jar  target/
echo ++++++++++++++++++release_flag=$release_flag++++++++++++++++++++
upload_file_ftp $ph_ftp_dir/$now_time/ public $release_flag  #只有正式环境的包才在ftp上备份完整包
cd $sdk_path
rm target -rf
mv target_tmp target

upload_file_ftp $ph_ftp_dir/ $now_time $release_flag  #只有正式环境的包才在ftp上备份完整包
cd $sdk_path
echo now_cur_path=`pwd`
version_jid=`cat sdk_config |grep jid |awk -F "=" '{print $2}'`
build_appid=`cat sdk_config |grep build_appid |awk -F "=" '{print $2}'`

mkdir "$now_time"_phoenix_sdk
cp -rn public/* "$now_time"_phoenix_sdk
cd "$now_time"_phoenix_sdk/
md5sum * > md5sum.txt
zip_all_name="$now_time"_phoenix_sdk.zip
zip -r $zip_all_name *
echo will upload file $zip_all_name to ftp server dir $phoenix_path
sshpass -p $ftp_psw  scp  $zip_all_name $phoenix_path/
[ $? -ne 0 ] && error_message="upload to cdn failed,exit" && Error_Msg "$error_message"
all_sdk_url="$sdk_server"/$zip_all_name
echo all_sdk_url=$all_sdk_url
cd $sdk_path

update_name="$now_time"_"update".zip
cp -rn "$now_time"/update.* "$update_name"
update_md5sum=`md5sum "$update_name" | awk -F " " '{print $1}' `
echo will upload file $update_name to ftp server dir $phoenix_path
sshpass -p $ftp_psw  scp  "$update_name" $phoenix_path/
[ $? -ne 0 ] && error_message="upload to cdn failed,exit" && Error_Msg "$error_message"
update_url="$sdk_server"/$update_name
echo update_url=$update_url

so_name="$now_time"_so.zip
cp "$now_time"/libs.zip $so_name
so_md5sum=`md5sum "$so_name" |awk -F " " '{print $1}'`
echo will upload file "$so_name" to ftp server dir $phoenix_path
sshpass -p $ftp_psw  scp  "$so_name" $phoenix_path/
[ $? -ne 0 ] && error_message="upload to cdn failed,exit" && Error_Msg "$error_message"
so_url="$sdk_server"/$so_name
echo so_url=$so_url
curl -H "Content-Type:application/json"  -X POST --data '{"dlinfo": [{"result_path": "'$all_sdk_url'","jid": "'$version_jid'","aversion": "null","bversion": "null","furl": "'$update_url'","fmd5": "'$update_md5sum'","apkurl":"null","apkmd5":"null","purl": "null","pmd5": "null","appid": "'$build_appid'" }]}' $notify_url

#curl -H "Content-Type:application/json"  -X POST --data '{"dlinfo2": [{"result_path": "'$all_sdk_url'","jid": "'$version_jid'","aversion": "'$sdk_v1'","bversion": "'$sdk_v2'","furl": "'$update_url'","fmd5": "'$update_md5sum'","purl": "'$so_url'","pmd5": "'$so_md5sum'" }]}' $notify_url
